<template>
  <div class="starrocks-cps-form">
    <el-form label-width="140px" :model="localValue">
      <section class="form-section">
        <div class="section-title">
          <el-icon class="data-source-icon"><Histogram /></el-icon>
          <span>数据源与时间</span>
        </div>
        <el-form-item label="StarRocks 数据源" required>
          <DataSourceSelector
            v-model="dataSourceIdForSelector"
            service-type="starrocks"
            placeholder="请选择数据源"
          />
        </el-form-item>
        <ReportTimeRangePicker
          v-model="localValue.time_range"
          @change="emitParams"
        />
      </section>

      <section class="form-section">
        <div class="section-title">
          <el-icon class="platform-icon"><List /></el-icon>
          <span>平台选择</span>
        </div>
        
        <!-- 平台选择容器 -->
        <div class="platform-selection-container">
          <!-- 平台多选框组 -->
          <el-checkbox-group 
            v-model="localValue.platform_selection.selected_platforms" 
            @change="emitParams"
            class="platform-checkbox-group"
          >
            <div class="platform-row">
              <el-checkbox 
                v-for="platform in platformOptions" 
                :key="platform.value"
                :label="platform.value"
                class="platform-checkbox"
              >
                <div class="platform-item">
                  <el-icon class="platform-icon">
                    <component :is="platform.icon" />
                  </el-icon>
                  <span class="platform-name">{{ platform.label }}</span>
                  <span class="platform-code">({{ platform.value }})</span>
                </div>
              </el-checkbox>
            </div>
          </el-checkbox-group>
          
          <!-- 快捷操作按钮 -->
          <div class="quick-actions">
            <el-tooltip :content="localValue.platform_selection.include_summary ? '点击移除平台汇总数据' : '点击添加平台汇总数据'" placement="top">
              <el-button 
                size="small" 
                :type="localValue.platform_selection.include_summary ? 'primary' : 'default'"
                @click="toggleSummary"
              >
                <el-icon><DataAnalysis /></el-icon>
                {{ localValue.platform_selection.include_summary ? '已包含汇总' : '不包含汇总' }}
              </el-button>
            </el-tooltip>
            <el-button size="small" @click="selectAllPlatforms">
              <el-icon><Select /></el-icon>
              全选
            </el-button>
            <el-button size="small" @click="clearAllPlatforms">
              <el-icon><Close /></el-icon>
              清空
            </el-button>
            <el-button size="small" type="primary" @click="selectCommonPlatforms">
              <el-icon><Star /></el-icon>
              常用平台
            </el-button>
          </div>
        </div>
        
        <!-- 选中平台预览 -->
        <div v-if="localValue.platform_selection.selected_platforms.length > 0" class="selected-preview">
          <div class="preview-header">
            <el-icon><View /></el-icon>
            <span>已选择平台 ({{ localValue.platform_selection.selected_platforms.length }})</span>
          </div>
          <div class="preview-content">
            <el-tag 
              v-for="platform in localValue.platform_selection.selected_platforms" 
              :key="platform"
              type="info"
              size="small"
              class="platform-tag"
              closable
              @close="removePlatform(platform)"
            >
              {{ getPlatformName(platform) }}
            </el-tag>
            <el-tag v-if="localValue.platform_selection.include_summary" type="success" size="small" class="summary-tag">
              <el-icon><DataAnalysis /></el-icon>
              汇总
            </el-tag>
          </div>
        </div>
        
        <!-- 平台统计信息 -->
        <div class="platform-stats">
          <el-alert
            v-if="localValue.platform_selection.selected_platforms.length === 0"
            title="请至少选择一个平台"
            type="warning"
            :closable="false"
            show-icon
          />
          <el-alert
            v-else
            :title="`已选择 ${localValue.platform_selection.selected_platforms.length} 个平台，${localValue.platform_selection.include_summary ? '包含' : '不包含'}汇总数据`"
            type="success"
            :closable="false"
            show-icon
          />
        </div>
      </section>

      <section class="form-section">
        <div class="section-title">
          <el-icon class="threshold-icon"><Tickets /></el-icon>
          <span>阈值配置</span>
        </div>
        
        <div class="threshold-container">
          <!-- 同步率阈值设置 -->
          <div class="threshold-item">
            <div class="item-header">
              <el-icon><Histogram /></el-icon>
              <span>同步率阈值 (%)</span>
              <el-tooltip content="当同步率低于此阈值时，数据状态将显示为'同步率过低'" placement="top">
                <el-icon class="help-icon"><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
            
            <div class="threshold-control">
              <el-slider
                v-model="localValue.threshold_config.sync_rate_threshold"
                :min="0"
                :max="100"
                :step="1"
                :marks="thresholdMarks"
                :format-tooltip="formatTooltip"
                @change="emitParams"
                class="threshold-slider"
              />
              
              <div class="threshold-input-group">
                <el-input-number
                  v-model="localValue.threshold_config.sync_rate_threshold"
                  :min="0"
                  :max="100"
                  :step="1"
                  controls-position="right"
                  @change="emitParams"
                  class="threshold-input"
                />
                <span class="unit">%</span>
              </div>
            </div>
          </div>
          
          <!-- 快捷阈值设置 -->
          <div class="quick-thresholds">
            <div class="quick-header">
              <el-icon><Star /></el-icon>
              <span>快捷设置</span>
            </div>
            <div class="quick-buttons">
              <el-button 
                v-for="preset in thresholdPresets" 
                :key="preset.label"
                size="small"
                :type="preset.value === localValue.threshold_config.sync_rate_threshold ? 'primary' : 'default'"
                @click="setThreshold(preset.value)"
              >
                {{ preset.label }}
              </el-button>
            </div>
          </div>
          
          <!-- 阈值预览 -->
          <div class="threshold-preview">
            <div class="preview-header">
              <el-icon><View /></el-icon>
              <span>阈值效果预览</span>
            </div>
            <div class="preview-content">
              <div class="preview-item">
                <span class="label">当前阈值:</span>
                <el-tag type="primary" size="small">{{ localValue.threshold_config.sync_rate_threshold }}%</el-tag>
              </div>
              <div class="status-examples">
                <div class="status-item normal">
                  <el-icon color="#67c23a"><CircleCheck /></el-icon>
                  <span>正常: ≥ {{ localValue.threshold_config.sync_rate_threshold }}%</span>
                </div>
                <div class="status-item warning">
                  <el-icon color="#e6a23c"><Warning /></el-icon>
                  <span>同步率过低: 0% ~ {{ localValue.threshold_config.sync_rate_threshold - 1 }}%</span>
                </div>
                <div class="status-item error">
                  <el-icon color="#f56c6c"><CircleClose /></el-icon>
                  <span>未同步: 0%</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      <section class="form-section">
        <div class="section-title">
          <el-icon class="display-fields-icon"><Filter /></el-icon>
          <span>显示字段</span>
        </div>
        <el-checkbox-group
          v-model="localValue.display_fields"
          class="display-fields"
          @change="emitParams"
        >
          <el-checkbox
            v-for="field in displayFieldOptions"
            :key="field.value"
            :label="field.value"
          >
            {{ field.label }}
          </el-checkbox>
        </el-checkbox-group>

        <!-- 平台名称显示方式开关 -->
        <el-row :gutter="16" class="platform-display-toggle-row">
          <el-col :span="12">
            <div class="platform-display-toggle-title">
              <el-icon><View /></el-icon>
              <span>平台名称使用中文</span>
            </div>
          </el-col>
          <el-col :span="12" class="platform-display-toggle-switch">
            <el-switch
              v-model="localValue.use_chinese_platform_name"
              @change="emitParams"
            />
          </el-col>
        </el-row>

        <el-row :gutter="16" class="field-label-toggle-row">
          <el-col :span="12">
            <div class="field-label-toggle-title">
              <el-icon><Tickets /></el-icon>
              <span>启用字段标签设置</span>
            </div>
          </el-col>
          <el-col :span="12" class="field-label-toggle-switch">
            <el-switch v-model="fieldLabelsEnabled" />
          </el-col>
        </el-row>

        <template v-if="fieldLabelsEnabled">
          <el-card shadow="never" class="field-label-card">
            <div class="field-label-help">
              自定义字段的中文显示名称，用于报表输出。留空则使用默认名称。
            </div>
            <el-table :data="fieldLabelsTable" border size="small" style="width: 100%" class="field-label-table">
              <el-table-column prop="fieldName" label="英文字段名" width="200">
                <template #default="{ row }">
                  <code class="field-code">{{ row.fieldName }}</code>
                </template>
              </el-table-column>
              <el-table-column prop="defaultLabel" label="默认中文名" width="180">
                <template #default="{ row }">
                  <span class="default-label">{{ row.defaultLabel }}</span>
                </template>
              </el-table-column>
              <el-table-column label="自定义中文名">
                <template #default="{ row }">
                  <el-input
                    v-model="row.customLabel"
                    placeholder="留空使用默认名称"
                    size="small"
                    clearable
                    class="custom-input"
                    @change="handleFieldLabelChange(row.fieldName, row.customLabel)"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </template>
      </section>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, watch, defineExpose, computed, ref, onMounted } from 'vue'
import { 
  Filter, Histogram, List, Tickets, Select, Close, Star, DataAnalysis, 
  QuestionFilled, View, ShoppingBag, Shop, ShoppingCart, VideoPlay, 
  Box, Goods, MoreFilled, CircleCheck, CircleClose, Warning
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import DataSourceSelector from '../../shared/DataSourceSelector.vue'
import ReportTimeRangePicker from '../../shared/ReportTimeRangePicker.vue'
import type { TemplateMeta } from '../registry'
import api from '@/utils/api'

interface CpsParams {
  data_source_config: {
    data_source_id: number | null
  }
  platform_selection: {
    selected_platforms: string[]
    include_summary: boolean
  }
  time_filter?: {
    time_range_type: string
    time_start: string | null
    time_end: string | null
  }
  time_range: {
    time_range_type: string
    time_start: string | null
    time_end: string | null
  }
  // 添加根级别的 time_range_type, time_start, time_end 字段
  time_range_type?: string
  time_start?: string | null
  time_end?: string | null
  threshold_config: {
    sync_rate_threshold: number
  }
  display_fields: string[]
  field_labels?: Record<string, string>
  // 是否在报表中使用中文平台名称
  use_chinese_platform_name?: boolean
}

const props = defineProps<{
  modelValue: CpsParams | null
  templateMeta?: TemplateMeta | null
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: CpsParams): void
  (e: 'validate', payload: { valid: boolean; errors: string[] }): void
}>()

const defaultValue = (): CpsParams => ({
  data_source_config: {
    data_source_id: null
  },
  platform_selection: {
    selected_platforms: ['dy'],
    include_summary: true
  },
  time_range: {
    time_range_type: 'all',
    time_start: null,
    time_end: null
  },
  time_filter: {
    time_range_type: 'all',
    time_start: null,
    time_end: null
  },
  threshold_config: {
    sync_rate_threshold: 80
  },
  display_fields: [
    'platform_summary',
    'platform',
    'source_total_count',
    'dws_total_count',
    'dws_on_sale_count',
    'dws_off_sale_count',
    'sync_rate',
    'data_status'
  ],
  field_labels: {},
  use_chinese_platform_name: true
})

const localValue = reactive<CpsParams>({
  ...defaultValue(),
  ...(props.modelValue || {})
})

// 用于 DataSourceSelector 的计算属性，将 null 转换为 undefined
const dataSourceIdForSelector = computed({
  get: () => localValue.data_source_config.data_source_id ?? undefined,
  set: (value: number | undefined) => {
    localValue.data_source_config.data_source_id = value ?? null
    emitParams()
  }
})

// 默认平台选项（作为后备）
const defaultPlatformOptions = [
  { value: 'tb', label: '淘宝联盟 (tb)', icon: 'ShoppingBag' },
  { value: 'tbc', label: '淘宝招商团长 (tbc)', icon: 'Shop' },
  { value: 'tbb', label: '淘宝商单广场 (tbb)', icon: 'ShoppingCart' },
  { value: 'dy', label: '抖音好单库 (dy)', icon: 'VideoPlay' },
  { value: 'dyc', label: '抖音团长 (dyc)', icon: 'VideoPlay' },
  { value: 'jd', label: '京东联盟 (jd)', icon: 'Box' },
  { value: 'pdd', label: '多多进宝 (pdd)', icon: 'Goods' },
  { value: 'vph', label: '唯品会开放平台 (vph)', icon: 'MoreFilled' }
]

// 平台选项（从 API 获取或使用默认值）
const platformOptions = ref<Array<{ value: string; label: string; icon: string }>>(defaultPlatformOptions)

// 图标映射
const iconMap: Record<string, string> = {
  'tb': 'ShoppingBag',
  'tbc': 'Shop',
  'tbb': 'ShoppingCart',
  'dy': 'VideoPlay',
  'dyc': 'VideoPlay',
  'jd': 'Box',
  'pdd': 'Goods',
  'vph': 'MoreFilled'
}

// 从 API 获取平台列表
const fetchPlatformList = async () => {
  try {
    const templateCode = 'cps_data_quality_monitor'
    const response = await api.get(`/reports/templates/${templateCode}/platforms`)
    
    if (response.data?.success && response.data?.data) {
      const platforms = response.data.data
      // 将后端返回的格式转换为前端需要的格式
      platformOptions.value = platforms.map((p: { value: string; label: string }) => ({
        value: p.value,
        label: `${p.label} (${p.value})`,
        icon: iconMap[p.value] || 'MoreFilled'
      }))
    }
  } catch (error: any) {
    console.warn('[StarrocksCpsForm] 获取平台列表失败，使用默认列表:', error)
    // API 调用失败时使用默认列表，不显示错误消息（保持向后兼容）
    platformOptions.value = defaultPlatformOptions
  }
}

// 组件挂载时获取平台列表
onMounted(() => {
  fetchPlatformList()
})

// 常用平台配置
const commonPlatforms = ['dy', 'tb', 'jd', 'pdd']

const displayFieldOptions = [
  { value: 'platform_summary', label: '平台汇总' },
  { value: 'platform', label: '平台' },
  { value: 'source_layer', label: '原始层(源表)' },
  { value: 'source_total_count', label: '原始层商品总数' },
  { value: 'dws_total_count', label: '目标表商品总数' },
  { value: 'dws_on_sale_count', label: '目标表上架商品数' },
  { value: 'dws_off_sale_count', label: '目标表下架商品数' },
  { value: 'sync_rate', label: '同步率' },
  { value: 'data_status', label: '数据状态' }
]

const displayFieldOrder = displayFieldOptions.map((opt) => opt.value)

const sortDisplayFields = () => {
  if (!Array.isArray(localValue.display_fields)) {
    localValue.display_fields = []
  }
  const uniqueSelected = Array.from(new Set(localValue.display_fields))
  const sorted: string[] = []

  displayFieldOrder.forEach((field) => {
    if (uniqueSelected.includes(field)) {
      sorted.push(field)
    }
  })

  uniqueSelected.forEach((field) => {
    if (!sorted.includes(field)) {
      sorted.push(field)
    }
  })

  const changed =
    sorted.length !== localValue.display_fields.length ||
    sorted.some((field, idx) => field !== localValue.display_fields[idx])

  if (changed) {
    localValue.display_fields = sorted
  }
}

const inferRangeType = (start: string | null, end: string | null, provided?: string) => {
  if (provided) return provided
  if (start && end) return 'custom'
  return 'all'
}

function syncRootTimeRange() {
  const rootStart = (localValue as any).time_start ?? null
  const rootEnd = (localValue as any).time_end ?? null
  const rootType = (localValue as any).time_range_type
  
  let tr = localValue.time_range || localValue.time_filter
  if (!tr && (rootStart !== null || rootEnd !== null)) {
    tr = {
      time_range_type: inferRangeType(rootStart, rootEnd, rootType),
      time_start: rootStart,
      time_end: rootEnd
    }
  }
  if (!tr) {
    tr = defaultValue().time_range
  }
  
  const normalized = {
    time_range_type: inferRangeType(tr.time_start ?? null, tr.time_end ?? null, tr.time_range_type),
    time_start: tr.time_start ?? null,
    time_end: tr.time_end ?? null
  }
  
  localValue.time_range = normalized
  localValue.time_filter = { ...normalized }
  ;(localValue as any).time_range_type = normalized.time_range_type
  ;(localValue as any).time_start = normalized.time_start
  ;(localValue as any).time_end = normalized.time_end
}

// 将时间范围信息同步到根对象
const writeRootTimeRange = () => {
  if (localValue.time_filter) {
    // 将 time_filter 中的时间范围信息复制到根对象
    ;(localValue as any).time_range_type = localValue.time_filter.time_range_type
    ;(localValue as any).time_start = localValue.time_filter.time_start
    ;(localValue as any).time_end = localValue.time_filter.time_end
  }
}

sortDisplayFields()
writeRootTimeRange()

const emitParams = () => {
  sortDisplayFields()
  syncRootTimeRange()
  // 检查 field_labels 是否完全是默认值
  const isDefaultLabels = () => {
    if (!localValue.field_labels || !fieldLabelsEnabled.value) {
      return false
    }
    
    // 检查是否所有标签都是默认值
    for (const field of localValue.display_fields) {
      const option = displayFieldOptions.find((opt) => opt.value === field)
      if (option) {
        const currentLabel = localValue.field_labels[field]
        const defaultLabel = option.label
        if (currentLabel !== defaultLabel) {
          return false // 发现用户自定义的标签
        }
      }
    }
    return true // 全部都是默认值
  }
  
  // 根据开关状态和标签内容决定如何处理 field_labels
  if (fieldLabelsEnabled.value) {
    // 用户开启了开关，确保 field_labels 存在
    if (!localValue.field_labels) {
      localValue.field_labels = {}
    }
    // 自动生成 field_labels：根据 display_fields 和 displayFieldOptions 生成默认映射
    // 只填充缺失的字段标签，保留用户已填写的标签
    localValue.display_fields.forEach((field) => {
      // 如果该字段还没有标签，则使用默认标签
      if (!localValue.field_labels![field]) {
        const option = displayFieldOptions.find((opt) => opt.value === field)
        if (option) {
          localValue.field_labels![field] = option.label
        }
      }
    })
  } else {
    // 用户关闭了开关，清空 field_labels
    localValue.field_labels = {}
  }
  
  // 确保时间范围信息已同步到根对象
  writeRootTimeRange()
  
  // 调试日志
  console.log('[StarrocksCpsForm] emitParams - fieldLabelsEnabled:', fieldLabelsEnabled.value)
  console.log('[StarrocksCpsForm] emitParams - field_labels:', JSON.parse(JSON.stringify(localValue.field_labels)))
  
  // 创建深拷贝
  const payload = JSON.parse(JSON.stringify(localValue))

  // 兜底：如果根级别没有时间范围字段，则从 time_range 中补充，保证写库字段一致
  if (!payload.time_range_type && payload.time_range && payload.time_range.time_range_type) {
    payload.time_range_type = payload.time_range.time_range_type
  }
  if (!payload.time_start && payload.time_range && payload.time_range.time_start) {
    payload.time_start = payload.time_range.time_start
  }
  if (!payload.time_end && payload.time_range && payload.time_range.time_end) {
    payload.time_end = payload.time_range.time_end
  }

  // time_filter 仅用于组件内部兼容，不写入最终 JSON
  delete payload.time_filter
  
  emit('update:modelValue', payload)
}

// 平台操作方法
const getPlatformName = (platform: string) => {
  const option = platformOptions.value.find(opt => opt.value === platform)
  return option ? option.label : platform
}

const selectAllPlatforms = () => {
  localValue.platform_selection.selected_platforms = platformOptions.value.map(opt => opt.value)
  emitParams()
}

const clearAllPlatforms = () => {
  localValue.platform_selection.selected_platforms = []
  emitParams()
}

const selectCommonPlatforms = () => {
  localValue.platform_selection.selected_platforms = [...commonPlatforms]
  emitParams()
}

const removePlatform = (platform: string) => {
  const index = localValue.platform_selection.selected_platforms.indexOf(platform)
  if (index > -1) {
    localValue.platform_selection.selected_platforms.splice(index, 1)
    emitParams()
  }
}

const toggleSummary = () => {
  localValue.platform_selection.include_summary = !localValue.platform_selection.include_summary
  emitParams()
}

// 阈值相关数据和方法
const thresholdMarks = {
  50: '50%',
  70: '70%',
  80: '80%',
  90: '90%',
  95: '95%'
}

// 预设阈值选项
const thresholdPresets = [
  { label: '严格 (90%)', value: 90 },
  { label: '标准 (80%)', value: 80 },
  { label: '宽松 (70%)', value: 70 },
  { label: '极宽松 (50%)', value: 50 }
]

const formatTooltip = (value: number) => {
  return `${value}%`
}

const setThreshold = (value: number) => {
  localValue.threshold_config.sync_rate_threshold = value
  emitParams()
}

// 字段标签相关
const fieldLabelsTable = computed(() =>
  displayFieldOptions.map((opt) => ({
    fieldName: opt.value,
    defaultLabel: opt.label,
    customLabel: localValue.field_labels?.[opt.value] || ''
  }))
)

const fieldLabelsEnabled = ref(
  // 智能判断字段标签设置状态：
  // 1. 如果 field_labels 不存在或为空，说明用户没有启用设置
  // 2. 如果 field_labels 存在但全部是默认值，说明用户没有真正自定义，应该显示为关闭状态
  // 3. 如果 field_labels 存在且有用户自定义的内容，说明用户启用了设置
  (() => {
    if (!localValue.field_labels || Object.keys(localValue.field_labels).length === 0) {
      return false
    }
    
    // 检查是否所有标签都是默认值
    for (const field of localValue.display_fields) {
      const option = displayFieldOptions.find((opt) => opt.value === field)
      if (option) {
        const currentLabel = localValue.field_labels[field]
        const defaultLabel = option.label
        if (currentLabel !== defaultLabel) {
          return true // 发现用户自定义的标签，说明用户启用了设置
        }
      }
    }
    
    // 全部都是默认值，说明用户没有真正启用设置
    return false
  })()
)

const handleFieldLabelChange = (fieldName: string, value: string) => {
  if (!localValue.field_labels) {
    // eslint-disable-next-line no-extra-semi
    ;(localValue as any).field_labels = {}
  }
  if (value && value.trim()) {
    (localValue.field_labels as Record<string, string>)[fieldName] = value.trim()
  } else if (localValue.field_labels) {
    delete (localValue.field_labels as Record<string, string>)[fieldName]
  }
  emitParams()
}

watch(
  () => props.modelValue,
  (val) => {
    if (!val) return
    const next = JSON.parse(JSON.stringify(val))
    if (!next.time_range && next.time_filter) {
      next.time_range = { ...next.time_filter }
    }
    Object.assign(localValue, defaultValue(), next)
    syncRootTimeRange()
    sortDisplayFields()
    
    // 重新计算 fieldLabelsEnabled 状态
    if (!localValue.field_labels || Object.keys(localValue.field_labels).length === 0) {
      fieldLabelsEnabled.value = false
    } else {
      // 检查是否所有标签都是默认值
      let hasCustomLabels = false
      for (const field of localValue.display_fields) {
        const option = displayFieldOptions.find((opt) => opt.value === field)
        if (option) {
          const currentLabel = localValue.field_labels[field]
          const defaultLabel = option.label
          if (currentLabel !== defaultLabel) {
            hasCustomLabels = true
            break
          }
        }
      }
      fieldLabelsEnabled.value = hasCustomLabels
    }
  },
  { deep: true }
)

watch(
  fieldLabelsEnabled,
  (enabled) => {
    if (!enabled) {
      localValue.field_labels = {}
      emitParams()
    }
  }
)

watch(
  () => props.templateMeta,
  (meta) => {
    if (meta?.defaultParams) {
      const next = JSON.parse(JSON.stringify(meta.defaultParams))
      if (!next.time_range && next.time_filter) {
        next.time_range = { ...next.time_filter }
      }
      Object.assign(localValue, defaultValue(), next)
      syncRootTimeRange()
      sortDisplayFields()
      // 重新初始化 fieldLabelsEnabled 状态，使用智能判断逻辑
      if (!localValue.field_labels || Object.keys(localValue.field_labels).length === 0) {
        fieldLabelsEnabled.value = false
      } else {
        // 检查是否所有标签都是默认值
        let hasCustomLabels = false
        for (const field of localValue.display_fields) {
          const option = displayFieldOptions.find((opt) => opt.value === field)
          if (option) {
            const currentLabel = localValue.field_labels[field]
            const defaultLabel = option.label
            if (currentLabel !== defaultLabel) {
              hasCustomLabels = true
              break
            }
          }
        }
        fieldLabelsEnabled.value = hasCustomLabels
      }
    }
  },
  { immediate: true }
)

const validate = () => {
  const errors: string[] = []
  if (!localValue.data_source_config.data_source_id) {
    errors.push('请选择数据源')
  }
  if (!localValue.platform_selection.selected_platforms?.length) {
    errors.push('至少选择一个平台')
  }
  emit('validate', { valid: errors.length === 0, errors })
  return errors.length === 0
}

defineExpose({ validate })
</script>

<style scoped>
.form-section {
  margin-bottom: 24px;
  padding: 24px;
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  background: linear-gradient(135deg, #ffffff 0%, #fafbfc 100%);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.form-section:hover {
  border-color: #c0c4cc;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
  transform: translateY(-1px);
}

.section-title {
  display: flex;
  align-items: center;
  gap: 10px;
  font-weight: 600;
  margin-bottom: 20px;
  color: #1f2937;
  font-size: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #f0f0f0;
  position: relative;
}

.section-title::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 60px;
  height: 2px;
  background: linear-gradient(90deg, #409eff, #67c23a);
  border-radius: 1px;
}

.form-section:nth-child(1) .section-title::after {
  background: linear-gradient(90deg, #409eff, #67c23a);
}

.form-section:nth-child(2) .section-title::after {
  background: linear-gradient(90deg, #67c23a, #85ce61);
}

.form-section:nth-child(3) .section-title::after {
  background: linear-gradient(90deg, #e6a23c, #f7ba2a);
}

.form-section:nth-child(4) .section-title::after {
  background: linear-gradient(90deg, #f56c6c, #ff8b8b);
}

.section-title .el-icon {
  font-size: 18px;
  color: #409eff;
}

.data-source-icon {
  color: #409eff;
}

.platform-icon {
  color: #67c23a;
}

.threshold-icon {
  color: #e6a23c;
}

.display-fields-icon {
  color: #f56c6c;
}

.form-section :deep(.el-form-item) {
  margin-bottom: 20px;
}

.form-section :deep(.el-form-item__label) {
  font-weight: 500;
  color: #374151;
  line-height: 32px;
}

.form-section :deep(.el-select) {
  width: 100%;
}

.form-section :deep(.el-select .el-input__inner) {
  border-radius: 8px;
  border: 1px solid #d1d5db;
  transition: all 0.3s ease;
}

.form-section :deep(.el-select .el-input__inner:focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.form-section :deep(.el-switch) {
  --el-switch-on-color: #409eff;
}

.form-section :deep(.el-switch__core) {
  border-radius: 12px;
}

.form-section :deep(.el-checkbox) {
  margin-right: 16px;
  margin-bottom: 8px;
}

.form-section :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #409eff;
  border-color: #409eff;
}

.display-fields {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.platform-display-toggle-row {
  margin: 20px 0 12px 0;
}

.platform-display-toggle-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: #303133;
}

.platform-display-toggle-switch {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

/* 平台选择样式 */
.platform-selection-container {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  background-color: #fafafa;
  margin-bottom: 16px;
}

.platform-checkbox-group {
  margin-bottom: 12px;
}

.platform-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 12px;
}

.platform-checkbox {
  margin: 0 !important;
}

.platform-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.platform-item:hover {
  background-color: rgba(64, 158, 255, 0.1);
}

.platform-icon {
  color: #409eff;
  font-size: 16px;
}

.platform-name {
  font-weight: 500;
  color: #303133;
}

.platform-code {
  font-size: 12px;
  color: #909399;
}

.quick-actions {
  display: flex;
  gap: 8px;
  padding-top: 12px;
  border-top: 1px solid #e4e7ed;
}

.summary-checkbox {
  margin: 0 !important;
}

.summary-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.help-icon {
  color: #909399;
  font-size: 14px;
  cursor: help;
}

.selected-preview {
  margin-top: 16px;
  padding: 12px;
  background-color: #f0f9ff;
  border: 1px solid #bfdbfe;
  border-radius: 8px;
}

.preview-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-weight: 500;
  color: #1e40af;
}

.preview-content {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.platform-tag {
  margin: 0 !important;
}

.summary-tag {
  margin: 0 !important;
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  border: none;
  color: #ffffff !important;
  font-weight: 600;
  
  /* 确保图标和文字都可见 */
  :deep(.el-icon) {
    color: #ffffff !important;
  }
  
  /* 增强对比度 */
  box-shadow: 0 2px 4px rgba(103, 194, 58, 0.3);
}

.platform-stats {
  margin-top: 12px;
}

/* 阈值配置样式 */
.threshold-container {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  background-color: #fafafa;
}

.threshold-item {
  margin-bottom: 20px;
}

.item-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-weight: 500;
  color: #303133;
}

.threshold-control {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.threshold-slider {
  flex: 1;
  min-width: 200px;
  margin: 0;
}

.threshold-input-group {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}

.threshold-input {
  width: 100px;
}

.unit {
  color: #909399;
  font-size: 14px;
}

.quick-thresholds {
  margin-bottom: 20px;
}

.threshold-preview {
  margin-bottom: 0;
  padding: 12px;
  background-color: #f0f9ff;
  border: 1px solid #bfdbfe;
  border-radius: 8px;
}

.threshold-preview .preview-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-weight: 500;
  color: #1e40af;
}

.threshold-preview .preview-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.threshold-preview .preview-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.threshold-preview .label {
  color: #606266;
  font-weight: 500;
}

.status-examples {
  display: flex;
  gap: 16px;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
}

.quick-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-weight: 500;
  color: #606266;
}

.quick-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .platform-row {
    grid-template-columns: 1fr;
  }
  
  .quick-actions {
    flex-wrap: wrap;
  }
  
  .threshold-control {
    flex-direction: column;
    gap: 12px;
  }
  
  .threshold-input-group {
    justify-content: center;
  }
  
  .status-examples {
    flex-direction: column;
    gap: 8px;
  }
  
  .quick-buttons {
    gap: 6px;
  }
}

/* 动画效果 */
.platform-checkbox :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #409eff;
  border-color: #409eff;
}

/* 字段标签设置样式 */
.field-label-toggle-row {
  margin: 20px 0 16px 0;
}

.field-label-toggle-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: #606266;
}

.field-label-toggle-switch {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.field-label-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background-color: #fafafa;
}

.field-label-help {
  margin-bottom: 16px;
  padding: 12px 16px;
  background-color: #f0f9ff;
  border: 1px solid #bfdbfe;
  border-radius: 6px;
  font-size: 14px;
  color: #1e40af;
  line-height: 1.5;
  display: flex;
  align-items: center;
  gap: 8px;
}

.field-label-help::before {
  content: '💡';
  font-size: 16px;
}

.default-label {
  color: #909399;
  font-size: 14px;
  font-weight: 500;
}

.field-label-card :deep(.el-card__body) {
  padding: 20px;
}

.field-code {
  background-color: #f5f7fa;
  padding: 4px 8px;
  border-radius: 4px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
  color: #e74c3c;
  font-weight: 600;
  border: 1px solid #e4e7ed;
}

.field-label-table {
  border-radius: 8px;
  overflow: hidden;
}

.field-label-table :deep(.el-table__header) {
  background-color: #f8f9fa;
}

.field-label-table :deep(.el-table__header th) {
  background-color: #f8f9fa;
  color: #303133;
  font-weight: 600;
  border-bottom: 2px solid #e4e7ed;
}

.field-label-table :deep(.el-table__row) {
  background-color: #ffffff;
}

.field-label-table :deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

.custom-input :deep(.el-input__inner) {
  border-radius: 6px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s ease;
}

.custom-input :deep(.el-input__inner:focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.platform-checkbox :deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
  color: #409eff;
}

/* 滑块样式优化 */
.threshold-slider :deep(.el-slider__runway) {
  background-color: #e4e7ed;
}

.threshold-slider :deep(.el-slider__bar) {
  background: linear-gradient(90deg, #f56c6c 0%, #e6a23c 50%, #67c23a 100%);
}

.threshold-slider :deep(.el-slider__button) {
  border-color: #409eff;
}

.threshold-slider :deep(.el-slider__stop) {
  background-color: #909399;
}
</style>

